import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { wxUser,address,merchant_admins } from './user.entity';
import { AppID,AppSecret } from '@/utils/index';
import axios from 'axios';
class userInfo {
    openid?: string;
    nickname?: string;
    avatar_url?: string;
    phone?: number;
}
interface MerchantQuery {
    username?: string;
    password?: string;
}
@Injectable()
export class UserService {
    constructor(
        @InjectRepository(wxUser) private readonly userRepository: Repository<wxUser>,
        @InjectRepository(address) private readonly addressRepository: Repository<address>,
        @InjectRepository(merchant_admins) private readonly merchantadminsRepository: Repository<merchant_admins>,
    ) { }
    // 查询单个用户信息
    findOne(id: number): Promise<wxUser | null> {
        return this.userRepository.findOneBy({ id });
    }
    //查询微信单个用户信息
    findwx(openid: string): Promise<wxUser | null> {
        return this.userRepository.findOneBy({ openid });
    }
    //修改微信用户信息
    async updateUser(userInfo: userInfo,id:number): Promise<any> {
        const queryConditions: Partial<wxUser> = {};
        if (userInfo.nickname) {
            queryConditions.nickname = userInfo.nickname;
        }
        if (userInfo.avatar_url) {
            queryConditions.avatar_url = userInfo.avatar_url;
        }
        if (userInfo.phone) {
            queryConditions.phone = userInfo.phone;
        }
        return await this.userRepository.update({id},queryConditions);
    }
    //查询个人后台用户
    findUser(userInfo:MerchantQuery): Promise<any> {
        const queryConditions: Partial<merchant_admins> = {};
        if (userInfo.username) {
            queryConditions.username = userInfo.username;
        }
        if (userInfo.password) {
            queryConditions.password = userInfo.password;
        }
        return this.merchantadminsRepository.findOneBy(queryConditions);
    }
    //查询微信用户列表
    findList(searchInfo: userInfo): Promise<wxUser[]> {
        const queryConditions: Partial<wxUser> = {};
        if (searchInfo.openid) {
            queryConditions.openid = searchInfo.openid;
        }
        if (searchInfo.nickname) {
            queryConditions.nickname = searchInfo.nickname;
        }
        if (searchInfo.phone) {
            queryConditions.phone = searchInfo.phone;
        }
        // 查询用户信息
        return this.userRepository.findBy(searchInfo);
    }
     // 创建微信用户
    async create(openid: string,code:string): Promise<wxUser> {
        let reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        let params = {
            appid: AppID,
            secret: AppSecret,
            code: code,
            grant_type: 'authorization_code'
          };
        const res = await axios.get(reqUrl, { params });
        // console.log(res.data);
        return await this.userRepository.save({
            openid:openid,
            nickname:res.data.nickname,
            avatar:res.data.headimgurl,
            phone:res.data.phone
        });
        // const user = new wxUser();
        // user.openid =openid;
        // return await this.userRepository.save(user);
    }
    //删除微信用户
    async delete(id: number): Promise<object> {
        try {
            // 删除用户信息
            await this.userRepository.delete(id);
            return {code:200,msg:"删除用户成功"}
        } catch (error) {
            throw new Error('删除用户时发生错误');
        }
    }
    //查询微信用户收货地址
    async addressList(info:object): Promise<object> {
        return await this.addressRepository.findBy(info); 
    }
    //新增或者修改微信用户收货地址
    async addressCreate(addressInfo:address): Promise<any> {
        if (addressInfo.id) {
            if(addressInfo.isDefault){
                await this.addressRepository.update({}, { isDefault: 0 });
            }
            return await this.addressRepository.update({ id: addressInfo.id }, addressInfo);
        } else {
            // 创建新地址
            return await this.addressRepository.save(addressInfo);
        }
    }
    //收货地址详情
    async addressDetail(id:number): Promise<address | null> {
        return  await this.addressRepository.findOneBy({ id });
    }
}
